;(function($) {

  RuS.SlideInMenu = function() {
    isOpen = false;

    $('#sim-handle').show().click(toggle);
    $('.sim-btn').click(click);
    $(window).on('resize', function() {
      if (isOpen) toggle();
    });
    // handleMove();

    // firefox fix (jQuery.browser.mozilla)
    $('#sim-handle, #sim-overlay, #sim-container, .sim-btn').css({ x: 0 });
  };

  var isOpen = false;

  // touch swipe fix
  var touchFix = function() {
    if ($.RusDevice.isAndroid()) {
      var elm = $('.hd-freq-text'), w = elm.width();
      setTimeout(function() {
        elm.width(w + 1);
      });
      setTimeout(function() {
        elm.width(w);
      }, 1000);
    }
  };

  var toggle = function() {
    if (isOpen) {
      frontend.model.gui.popup(false);
      close();
    }
    else {
      frontend.model.gui.popup(true);
      open();
    }
  };

  var open = function() {
    var $handle = $('#sim-handle');
    var $container = $('#sim-container');
    var width = $(window).width();

    $('#sim-overlay').show();
    $handle
        .addClass('active')
        .data({'opacity-before': $handle.css('opacity')})
        .transition({x: sim_padding_left - width, opacity: 0.9}, function() {
        });
    $container
        .show()
        .data({'opacity-before': $container.css('opacity')})
        .css({ right: -(width - sim_padding_left), width: width - sim_padding_left })
        .transition({x: sim_padding_left - width, opacity: 0.5}, function() {
          touchFix();
        });

    $('.sim-btn:not([sim-set])').each(function(idx) {
      $(this).transition(_.extend(destPosition.start($(this), idx), { opacity: 0.9 }));
    });
    isOpen = true;
  };

  var close = function() {
    var $handle = $('#sim-handle');
    var $container = $('#sim-container');

    $('#sim-overlay').hide();
    $handle
        .removeClass('active')
        .transition({x: 0, opacity: $handle.data('opacity-before')}, function() {
        });
    $container
        .transition({x: 0, opacity: $container.data('opacity-before')}, function() {
          $container.hide();
        });
    $('.sim-btn').removeClass('anchored').each(function(idx) {
      $(this)
          .transition({ x: 0, y: 0, opacity: 0.9 }, function() {
            $(this).hide();
          });
    });
    isOpen = false;
  };

  var toggleSet = function(name, el) {
    if (el.hasClass('anchored')) {
      $('.sim-btn:not([sim-data="set:N"]):not([sim-set="N"])'.replace(/N/g, name)).show().transition({ opacity: 0.9 });
      el.removeClass('anchored').transition(destPosition.move(el, 0));
      $('.sim-btn[sim-set=N]'.replace(/N/g, name)).each(function(idx) {
        $(this).transition({ x: 0, y: 0, opacity: 0.9 });
      });
    }
    else {
      $('.sim-btn:not([sim-data="set:N"]):not([sim-set="N"])'.replace(/N/g, name)).transition({ opacity: 0 }, function() {
        $(this).hide();
      });
      el.addClass('anchored').transition(destPosition.move(el, 0));
      $('.sim-btn[sim-set=N]'.replace(/N/g, name)).each(function(idx) {
        $(this).transition(_.extend(destPosition.start($(this), idx + 3), { opacity: 0.9 }), function() {
          touchFix();
        });
      });
    }
  };

  var click = function(e) {
    var btn = $(e.target).closest('.sim-btn');
    var self = this;
    btn.addClass('active');
    setTimeout(function() {
      btn.removeClass('active');
      var data = btn.attr('sim-data');
      if (data) {
        data = data.split(':');
        if (data[0] !== 'set') {
          toggle();
        }
        switch (data[0]) {
          case 'anchor':
            $('[sim-anchor="' + data[1] + '"]').click();
            break;
          case 'url':
            app.navigate(data[1], true);
            break;
          case 'set':
            toggleSet(data[1], btn);
            break;
          default:
        }
      }
    }, 100);
  };

  var sim_padding_left = 100;

  var destPosition = (function() {
    var m, n;
    switch ($('.sim-btn').length) {
      case 1:
      case 2:
      case 3:
      case 4:
        // m = 2, n = 2, p = 50;
        m = 3, n = 3, p = 20;
        break;
      case 5:
      case 6:
        // m = 3, n = 2, p = 40;
        m = 3, n = 3, p = 20;
        break;
      default:
        m = 3, n = 3, p = 20;
    }

    var container = $(window);

    return {
      start: function(el, idx) {

        var idx = el.attr('sim-pos') || idx;

        var w = container.width() - sim_padding_left;
        var h = container.height();
        var btn_w = ~~(w / m - p * 2);
        var btn_h = ~~(h / n - p * 2);
        var x = ~~(sim_padding_left + w + (Math.floor(idx / m) + 0.5) * (w / m) - btn_w / 2);
        var y = ~~((idx % m + 0.5) * (h / n) - btn_h / 2);
        var s = el.show().css({ width: btn_w, height: btn_h, left: x, top: y }).position();

        var image = el.attr('sim-image');
        var icon = el.attr('sim-icon');

        if (image) {
          el.css({
            'background-image': 'url(' + image + ')',
            'background-position': '20px center',
            'background-repeat': 'no-repeat',
            'background-size': '50px'
          }).find('div').css({
                'padding': '0 10px 0 80px',
                'text-align': 'left'
              });
        } else if (icon) {

          el.find('i').remove();
          el.prepend('<i class="' + icon + '"></i>');
          el.css('textAlign', 'left')
              .find('div').css({
                //'padding':'0 10px 0 75px',
                'textAlign': 'left'
              });
        }

        return {
          x: ~~(sim_padding_left + (Math.floor(idx / m) + 0.5) * (w / m) - s.left - el.outerWidth() / 2),
          y: ~~((idx % m + 0.5) * (h / n) - s.top - el.outerHeight() / 2)
        };
      },

      move: function(el, idx) {
        var w = container.width() - sim_padding_left;
        var h = container.height();
        var s = el.position();

        return {
          x: ~~(-w + sim_padding_left + (Math.floor(idx / m) + 0.5) * (w / m) - s.left - el.outerWidth() / 2)
          //        y: ~~((idx % m + 0.5) * (h / n) - s.top - el.outerHeight() / 2)
        };
      }
    };
  })();

})(jQuery);
